# -*- encoding=utf8 -*-

import os
import sys
import json
import util
import GithubAPI

if __name__ == "__main__":
    # 本地specs文件夹路径
    search_index_path = sys.path[0] + "/../search_index.json"
    private_pod_specs_dir = util.ct_getPrivateSpecsFolder()
    if not private_pod_specs_dir:
        sys.exit("私有Podspec仓库文件夹不存在....")
        
    # 获取索引文件内容
    indexContent = util.ct_getFileContent(search_index_path)
    if indexContent:
        podList = json.loads(indexContent)
        
        for podInfo in podList:
            podName = podInfo["name"]            
            podPath = podInfo["path"]
            lastestVersion = podInfo["lastestVersion"]
            
            print("正在查询[%s，本地最新版本: %s]..." % (podName, lastestVersion))
            
            vList = GithubAPI.ct_getCocoaPodsRepoContents(podPath);
            if not vList: continue
            
            serverVersionList = []
            for item in vList:
                if item["type"] == "dir":
                    serverVersionList.append(item["name"])
            
            serverLastestVersion = util.ct_findBiggestVersion(serverVersionList)
            
            if len(serverLastestVersion) < 1: continue
            
            if util.ct_versionCompare(serverLastestVersion, lastestVersion) == 2:
                # 发现新版本
                folder = private_pod_specs_dir + podName + "/" + serverLastestVersion + "/"
                if not os.path.exists(folder):
                    os.makedirs(folder)
                
                file_name = podName + ".podspec.json"
                configJson = GithubAPI.ct_getCocoaPodsRepoFileContent(podPath + serverLastestVersion + "/" + file_name)
                if configJson and util.ct_writeToFile(folder + file_name, str(configJson)):
                    print("写入成功: " + folder + file_name)
